package controllers;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.GoogleAnalytic;

import models.GoogleAnalyticModel;

public class AnalyticServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/msg/page-not-found");
			return ;
		}
		
		GoogleAnalyticModel googleAnalyticModel = GoogleAnalyticModel.getInstance();
		GoogleAnalytic googleAnalytic = googleAnalyticModel.get(id);
		
		if (googleAnalytic == null) {
			response.sendRedirect("/msg/page-not-found");
			return ;
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public");
		response.addHeader("Cache-Control", "max-age=" + 60000);
		
		request.setAttribute("googleAnalytic", googleAnalytic);
		try {
			request.getRequestDispatcher("/pages/analytics.jsp").forward(request, response);
		} catch (ServletException e) {
			
		}
	}
}
